package com.example.travel.service.impl;

import com.example.travel.entity.Leave;
import com.example.travel.entity.User;
import com.example.travel.entity.Write;
import com.example.travel.entity.bo.WriteBO;
import com.example.travel.entity.dto.WriteDTO;
import com.example.travel.mapper.UserMapper;
import com.example.travel.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String updateInformation(User user) {
        int nameNUmber = userMapper.selectUsername(user);
        int emailNUmber = userMapper.selectEmail(user);

        if(nameNUmber >= 1){
            return "该账号已存在";
        }else if(emailNUmber >= 1){
            return "该邮箱已存在";
        }else {
            boolean updateInformation = userMapper.updateInformation(user);
            if(updateInformation){
                return "true";
            }
        }
        return "false";
    }

    @Override
    public boolean insertWrite(Write write) {
        return userMapper.insertWrite(write);
    }

    @Override
    public PageInfo<WriteBO> selectWrite(WriteDTO writeDTO) {
        PageHelper.startPage(writeDTO.getPageNum(),writeDTO.getPageSize());
        List<WriteBO> list = userMapper.selectWrite(writeDTO);
        System.out.println(writeDTO.getUserId());
        if(writeDTO.getUserId() == null){
            for (int i = 0; i < list.size(); i++) {
                String text = UserService.stripHtml(list.get(i).getText());
                list.get(i).setText(text);
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public WriteBO selectWriteParticulars(WriteDTO writeDTO) {
        return userMapper.selectWriteParticulars(writeDTO);
    }

    @Override
    public boolean insertLeave(Leave leave) {
        return userMapper.insertLeave(leave);
    }

    @Override
    public List<Leave> selectLeave() {
        return userMapper.selectLeave();
    }

    @Override
    public boolean updateWrite(WriteDTO writeDTO) {
        return userMapper.updateWrite(writeDTO);
    }

    @Override
    public boolean delWrite(WriteDTO writeDTO) {
        return userMapper.delWrite(writeDTO);
    }

    /**
     * 去除游记展示页面的HTML标签
     * @param content
     * @return
     */
    public  static String stripHtml(String content) {
        // <p>段落替换为换行
        content = content.replaceAll("<p .*?>", "\r\n");
        // <br><br/>替换为换行
        content = content.replaceAll("<br\\s*/?>", "\r\n");
        // 去掉其它的<>之间的东西
        content = content.replaceAll("\\<.*?>", "");
        // 去掉空格
        content = content.replaceAll(" ", "");
        return content;
    }


}
